package com.aurora.base.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public final class UploadUtil {

	public static String uploadImg(MultipartHttpServletRequest request,
			String imgpath) throws Exception {
		MultipartHttpServletRequest multipartRequest = request;
		CommonsMultipartFile file = (CommonsMultipartFile) request
				.getFile("img_file");
		String fileName = file.getOriginalFilename();
		int dot = fileName.lastIndexOf('.');
		String suffix = fileName.substring(dot).toLowerCase();// 后缀名
		// System.out.println(suffix);
		List fileTypes = new ArrayList();
		fileTypes.add(".jpg");
		fileTypes.add(".jpeg");
		fileTypes.add(".bmp");
		fileTypes.add(".gif");
		fileTypes.add(".png");
		if (!fileTypes.contains(suffix)) {
			return CreateResJosnUtil.createErrJson("只能上传图片").toString();
		}
		String ctxpath = request.getSession().getServletContext()
				.getRealPath("/");
		String imgPath = imgpath + System.currentTimeMillis() + suffix;
		File sf = new File(ctxpath + imgpath);
		if (!sf.exists()) {
			sf.mkdirs();
		}
		File dirpathFile = new File(ctxpath + imgPath);
		file.transferTo(dirpathFile);
		return CreateResJosnUtil.createSuccessJson(null,
				new JSONObject().put("url", imgPath)).toString();
	}

	public static String uploadXlsx(MultipartHttpServletRequest request,
			String imgpath) throws Exception {
		MultipartHttpServletRequest multipartRequest = request;
		CommonsMultipartFile file = (CommonsMultipartFile) request
				.getFile("img_file");
		String fileName = file.getOriginalFilename();
		int dot = fileName.lastIndexOf('.');
		String suffix = fileName.substring(dot).toLowerCase();// 后缀名
		// System.out.println(suffix);
		List fileTypes = new ArrayList();
		fileTypes.add(".xlsx");
		if (!fileTypes.contains(suffix)) {
			return CreateResJosnUtil.createErrJson("只能上传xlsx文件").toString();
		}
		String ctxpath = request.getSession().getServletContext()
				.getRealPath("/");
		String imgPath = imgpath + System.currentTimeMillis() + suffix;
		File sf = new File(ctxpath + imgpath);
		if (!sf.exists()) {
			sf.mkdirs();
		}
		File dirpathFile = new File(ctxpath + imgPath);
		file.transferTo(dirpathFile);
		return ctxpath + imgPath;
	}
}
